package com.hoo.controller.account;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hoo.common.constant.Constant;
import com.hoo.entity.equipment.Advertise;
import com.hoo.entity.equipment.InvoiceMachine;
import com.hoo.entity.equipment.InvoiceRule;
import com.hoo.entity.equipment.Venue;
import com.hoo.exception.SaleException;
import com.hoo.form.equipment.AdvertiseForm;
import com.hoo.form.equipment.InvoiceMachineForm;
import com.hoo.form.equipment.VenueForm;
import com.hoo.service.equipment.AdvertiseService;
import com.hoo.service.equipment.InvoiceMachineService;
import com.hoo.service.equipment.VenueService;
import com.hoo.util.DateUtils;
import com.hoo.util.ExtBatchRename;
import com.hoo.util.PaginationSupport;

@Controller
@RequestMapping("/equipment")
public class equipmentController extends BaseController {
	
	@Autowired
	InvoiceMachineService invoiceMachineService;
	
	@Autowired
	VenueService venueService;
	
	@Autowired
	AdvertiseService advertiseService;
	
	private static String pathString =Constant.WINDOSFILEPATH;
	
	
	@RequestMapping(value="/manage_machine",method=RequestMethod.GET)
	public ModelAndView manageMachine(){
		return new ModelAndView("equipment/manageMachine");
	}
	
	/**
	 * 取票机列表展示
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/manage_machine",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> doManageMachine(InvoiceMachineForm form){
		PaginationSupport<InvoiceMachine> ps = this.invoiceMachineService.searchInvoiceMachine(form);
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}
	
	/**
	 * 添加/修改取票机
	 * @param type
	 * @param id
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/update_machine/{type}/{id}", method = RequestMethod.GET)
	public String updateMachine(@PathVariable("type") String type,@PathVariable("id") Integer id, Model model, HttpServletRequest request) {
		if("update".equals(type)){
			model.addAttribute("machine",this.invoiceMachineService.getInvoiceMachineById(id));
		}else {
			type="add";
		}
		model.addAttribute("venueList", this.venueService.getAllVenue());
		model.addAttribute("advertiseList",this.advertiseService.getAllAdvertise());
		model.addAttribute("operationType", type);
		return "equipment/updateMachine";
	}
	
	
	@RequestMapping(value = "/delete_machine", method = RequestMethod.POST)
	@ResponseBody
	public String deleteMachine(@RequestParam int id ,HttpServletRequest request) {
		InvoiceMachine invoiceMachine = this.invoiceMachineService.getInvoiceMachineById(id);
		File file=new File(pathString+"\\"+"close"+invoiceMachine.getIp()+".bat");
		File file1=new File(pathString+"\\"+"wake"+invoiceMachine.getIp()+".bat");
		file.delete();
		logger.debug("delete invoiceMachine close file");
		file1.delete();
		logger.debug("delete invoiceMachine wake file");
		ExtBatchRename.updateFileContent("closeall.bat", "shutdown -m \\\\" + invoiceMachine.getIp() + "-f -s -t 30","");
		logger.debug("update invoiceMachine shutdown file");
		ExtBatchRename.updateFileContent("wakeall.bat", "wolcmd "+ invoiceMachine.getMacIp() + " " + invoiceMachine.getIp() + " " + invoiceMachine.getMask()+ " 7", "");
		logger.debug("update invoiceMachine wolcmd file");
		return String.valueOf(this.invoiceMachineService.deleteInvoiceMachine(id));
	}

	
	
	@RequestMapping(value = "/manage_venue", method = RequestMethod.GET)
	public String manageVenue(HttpServletRequest request) {
		return "equipment/manageVenue";
	}
	
	@RequestMapping(value = "/manage_venue", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doManageVenue(HttpServletRequest request) {
		PaginationSupport<Venue> ps = this.venueService.search();
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}
	
	@RequestMapping(value = "/update_venue/{type}/{id}", method = RequestMethod.GET)
	public String udpateVenue(@PathVariable("type") String type,@PathVariable("id") Integer id, Model model, HttpServletRequest request) {
		if("update".equals(type)){
			model.addAttribute("venue", this.venueService.getVenueById(id));
		}else {
			type="add";
		}
		model.addAttribute("operationType", type);
		return "equipment/updateVenue";
	}
	
	@RequestMapping(value = "/update_venue/{operationType}", method = RequestMethod.POST)
	@ResponseBody
	public String doUdpateVenue(VenueForm form ,@PathVariable("operationType") String operationType ,Model model, HttpServletRequest request) {
		String result="";
		if("update".equals(operationType)){
			result = this.venueService.updateVenue(form)==1?"success":"fail";
			logger.debug("update venue "+result);
			return result;
		}
		result =this.venueService.addVenue(form)==1?"success":"fail"; 
		logger.debug("update venue "+result);
		return result;
	}
	
	@RequestMapping(value = "/delete_venue", method = RequestMethod.POST)
	@ResponseBody
	public String deleteVenue(@RequestParam int id ,HttpServletRequest request) {
		return String.valueOf(this.venueService.deleteVenue(id));
	}
	
	@RequestMapping(value = "/manage_advertise", method = RequestMethod.GET)
	public String manageAdvertise(HttpServletRequest request) {
		return "equipment/manageAdvertise";
	}
	
	@RequestMapping(value = "/manage_advertise", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> doManageAdvertise(HttpServletRequest request) {
		PaginationSupport<Advertise> ps = this.advertiseService.search();
		return dataTableJson(ps.getTotalCount(), ps.getItems());
	}
	
	@RequestMapping(value = "/delete_advertise", method = RequestMethod.POST)
	@ResponseBody
	public String deleteAdvertise(@RequestParam int id ,HttpServletRequest request) {
		return String.valueOf(this.advertiseService.deleteAdvertiseById(id));
	}
	
	/**
	 * 判断对取票机的操作类型
	 * @param type
	 * @param id
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/update_advertise/{type}/{id}", method = RequestMethod.GET)
	public String udpateAdvertise(@PathVariable("type") String type,@PathVariable("id") Integer id, Model model, HttpServletRequest request) {
		if("update".equals(type)){
			model.addAttribute("advertise", this.advertiseService.getAdvertiseById(id));
		}else {
			type="add";
		}
		model.addAttribute("operationType", type);
		model.addAttribute("advertiseType", this.advertiseService.getAllAdvertiseType());
		return "equipment/updateAdvertise";
	}
	
	/**
	 * 取票机的增加修改操作
	 * @param form
	 * @param operationType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/update_advertise/{operationType}", method = RequestMethod.POST)
	@ResponseBody
	public String doUdpateAdvertise(AdvertiseForm form ,@PathVariable("operationType") String operationType ,Model model, HttpServletRequest request) {
		Map<String, String> imagePaths = upload(request);
		form.setImagePath(imagePaths.get("file"));
		form.setImagePath2(imagePaths.get("file2"));
		form.setImagePath3(imagePaths.get("file3"));
		if("update".equals(operationType)){
			return this.advertiseService.updateAdvertise(form)==1?Constant.SUCCESS:Constant.FAIL;
		}
		return this.advertiseService.insertAdvertise(form)==1?Constant.SUCCESS:Constant.FAIL;
	}
	
	
	/**
	 * 处理多文件上传
	 * @param request
	 * @return
	 */
	public Map<String,String> upload(HttpServletRequest request){
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		Map<String, String> imagePaths= new HashMap<String, String>();
		imagePaths.put("file", null);
		imagePaths.put("file2", null);
		imagePaths.put("file3", null);
		if(multipartResolver.isMultipart(request)){  
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            Iterator<String> iter = multiRequest.getFileNames();  
            while(iter.hasNext()){
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){  
                    if(file.getOriginalFilename().trim() !=""){  
                        String fileName =DateUtils.getDateString(new Date())+String.valueOf((Math.random()*1000))+".png";
                        imagePaths.put(file.getName(),Constant.imagePathFloder+fileName);
                        String path = request.getSession().getServletContext().getRealPath("advertiseImages"); 
                        File localFile = new File(path +"\\"+fileName);  
                        try {
							file.transferTo(localFile);
						} catch (IllegalStateException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}  
                    }  
                }  
            }  
		}
        return imagePaths;
	}
	
	/**
	 * 控制取票机的开关
	 * @param controType
	 * @param ip
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/controInvoiceMachine/{controType}/{ip}", method = RequestMethod.POST)
	@ResponseBody
	public String singleControComputer(@PathVariable("controllType") String controllType,@PathVariable("ip") String ip, Model model) {
		invoiceMachineService.controllComputer(controllType + ip + ".bat");
		return "equipment/monitorInvoiceMachine";
	}
	
	/**
	 *获取取票机列表
	 * @return
	 */
	@RequestMapping("/invoice_machine_list")
	public String monitorComputer(Model model) {
		//从数据库查询得到所有取票机的ip，位置，状态信息
		List<InvoiceMachine> invoiceMachines = this.invoiceMachineService.getAllInvoiceMachine();
		List<InvoiceMachineForm> list=this.invoiceMachineService.monitorInvoiceMachine(invoiceMachines);
		model.addAttribute("list", list);
		return "equipment/monitorInvoiceMachine";
	}
	
	
	/**
	 * 增加取票机
	 * @param ip
	 * @param mac  mac地址
	 * @param mask  子网掩码
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add_invoice_machine",method=RequestMethod.POST)
	@ResponseBody
	public String addComputer(@ModelAttribute InvoiceMachineForm form, Model model) {
		try {
			if(invoiceMachineService.insertInvoiceMachine(form)!=1){
				return Constant.FAIL;
			}
		} catch (Exception e) {
			System.err.println("exception");
			System.out.println(e);
			return Constant.FAIL;
		}
		try {
				ExtBatchRename.updateFileContent("close" + form.getIp() + ".bat","shutdown -m \\\\" +form.getIp() + "-f -s -t 30","shutdown -m \\\\" +form.getIp() + "-f -s -t 30");
				ExtBatchRename.updateFileContent("wake" + form.getIp() + ".bat", "wolcmd " +form.getMacIp()
						+ " " + form.getIp()+ " " + form.getMask() + " 7","wolcmd " +form.getMacIp()+ " " + form.getIp()+ " " + form.getMask() + " 7");
				ExtBatchRename.updateFileContent("closeall.bat", "shutdown -m \\\\" + form.getIp() + "-f -s -t 30", "shutdown -m \\\\" + form.getIp() + "-f -s -t 30");
				ExtBatchRename.updateFileContent("wakeall.bat", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7");
			
			/*ExtBatchRename.updateFile(pathString, "close" + form.getIp() + ".txt","shutdown -m \\\\" +form.getIp() + "-f -s -t 30");
			ExtBatchRename.updateFile(pathString, "wake" + form.getIp() + ".txt", "wolcmd " +form.getMacIp()
					+ " " + form.getIp()+ " " + form.getMask() + " 7");
			if(ExtBatchRename.checkFile("closeall.bat") && ExtBatchRename.checkFile("wakeall.bat")){
				ExtBatchRename.updateFileContent("closeall.txt", "shutdown -m  \\\\" + form.getIp() + "-f -s -t 30", "shutdown -m \\\\" + form.getIp() + "-f -s -t 30");
				ExtBatchRename.updateFileContent("wakeall.txt", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7");
			}else {
				ExtBatchRename.updateFile(pathString, "closeall.txt","shutdown -m \\\\" + form.getIp() + "-f -s -t 30");
				ExtBatchRename.updateFile(pathString, "wakeall.txt", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7");
			}*/
			// 更改文件后缀名
			//ExtBatchRename.reName(pathString, ".txt", ".bat");
			return Constant.SUCCESS;
		} catch (Exception e) {
			logger.info("创建控制电脑开关文件失败");
		}
		return Constant.FAIL;
	}

	/**
	 * 修改取票机信息
	 * @param form
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/update_invoice_machine",method = RequestMethod.POST)
	@ResponseBody
	public String updateComputer(InvoiceMachineForm form ,Model model,HttpServletRequest request) {
		try {
			if(invoiceMachineService.updateInvoiceMachine(form)!=1){
				return Constant.FAIL;
			}
			File file=new File(pathString+"close" + form.getOldip() + ".bat");
			if(!file.exists()){
				try {
					ExtBatchRename.updateFileContent("close" + form.getOldip() + ".bat", "shutdown -m \\\\" + form.getOldip() + "-f -s -t 30","shutdown -m \\\\" + form.getIp() + "-f -s -t 30");
					ExtBatchRename.updateFileContent("closeall.bat", "shutdown -m \\\\" + form.getOldip() + "-f -s -t 30", "shutdown -m \\\\" + form.getIp() + "-f -s -t 30");
					ExtBatchRename.updateFileContent("wake" + form.getOldip() + ".bat","wolcmd "+ form.getOldmac() + " " + form.getOldip() + " " + form.getMask()+ " 7","wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7");
					ExtBatchRename.updateFileContent("wakeall.bat", "wolcmd "+ form.getOldmac()+ " " + form.getOldip() + " " + form.getMask()+ " 7", "wolcmd "+ form.getMacIp() + " " + form.getIp() + " " + form.getMask()+ " 7");
					ExtBatchRename.updateFileName("close192.168.1.500.bat", "close192.168.1.100.bat");
					ExtBatchRename.updateFileName("wake192.168.1.500.bat", "wake192.168.1.100.bat");
					return Constant.SUCCESS;
				}catch (Exception e) {
					logger.error("修改文件或文件名失败");
				}
			}
		} catch (SaleException e) {
			logger.error(e.getMessage());
		}
		
		return Constant.FAIL;
	}
	
	
	@RequestMapping(value="/check_venue_name",method=RequestMethod.POST)
	@ResponseBody
	public String checkVenueName(VenueForm form){
		if(null != this.venueService.getVenue(form)){
			return "existence";
		}
		return "inexistence";
	}
	
	
	/**
	 * 检查该场馆下是否有取票机
	 * @param venueId
	 * @return
	 */
	@RequestMapping(value="/check_exist_invoice_machine",method=RequestMethod.POST)
	@ResponseBody
	public String checkExistInvoiceMachine(@RequestParam String venueId){
		InvoiceMachineForm form=new InvoiceMachineForm();
		form.setVenueId(Integer.parseInt(venueId));
		if(this.invoiceMachineService.getInvoiceMachineCount(form) >0){
			return "exist";
		}
		return "inexistence";
	}
	
	@RequestMapping(value="/invoice_rule", method=RequestMethod.GET)
	public String invoiceRule(Model model){
		model.addAttribute("invoiceRule", invoiceMachineService.getInvoiceRule());
		return "equipment/invoiceRule";
	}
	
	@RequestMapping(value="/update_invoice_rule", method=RequestMethod.GET)
	public String updateInvoiceRule(Model model){
		model.addAttribute("invoiceRule", invoiceMachineService.getInvoiceRule());
		return "equipment/updateInvoiceRule";
	}
	
	
	/**
	 * 修改取票规则
	 * @param model
	 * @param rule
	 * @return
	 */
	@RequestMapping(value="/update_invoice_rule", method=RequestMethod.POST)
	@ResponseBody
	public String doUpdateInvoiceRule(Model model,InvoiceRule rule){
		if(1==invoiceMachineService.updateInvoiceRule(rule)){
			return Constant.SUCCESS;
		}
		return Constant.FAIL;
	}
	
	
	/**
	 * 检查取票机的ip是否已经存在
	 * @param model
	 * @param ip
	 * @param rule
	 * @return
	 */
	@RequestMapping(value="/check_invoice_machine_ip", method=RequestMethod.POST)
	@ResponseBody
	public String checkInvoiceMachineIp(Model model,@RequestParam String ip,InvoiceRule rule){
		InvoiceMachineForm form=new InvoiceMachineForm();
		form.setIp(ip);
		if(null == invoiceMachineService.getInvoiceMachine(form)){
			return "false";
		}
		return "true";
	}
}
